﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Sunny.UI;

namespace DevelopTool.Common
{
    /// <summary>
    /// 转换帮助类
    /// </summary>
    public static class ConvertHelper
    {

        /// <summary>
        /// Byte转Object，并解压缩
        /// </summary>
        /// <typeparam name="T">泛型对象</typeparam>
        /// <param name="bytes">需要解压的字节数组</param>
        /// <param name="deCompressType">解压缩类型</param>
        /// <returns></returns>
        public static T ByteToObject_Decompress<T>(this byte[] bytes)
        {
            if (bytes.Length <= 0) return default(T);

            return ByteToObject<T>(bytes.DeflateDecompress());
        }


        /// <summary>
        /// Object转Byte，并压缩
        /// </summary>
        /// <param name="obj">需要压缩的字节数组</param>
        /// <param name="compressType">压缩类型</param>
        /// <returns></returns>
        public static byte[] ObjectToByte_Compress(this object obj)
        {
            if (obj == null) return null;

            return ObjectToByte(obj).DeflateCompress();//Deflate算法
        }



        /// <summary>
        /// Byte转Object
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static T ByteToObject<T>(byte[] bytes)
        {
            if (bytes == null || bytes.Length <= 0) return default(T);
            object obj;
            using (MemoryStream memoryStream = new MemoryStream(bytes))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                obj = binaryFormatter.Deserialize(memoryStream);
            }
            return (T)obj;
        }


        /// <summary>
        /// Object转Byte
        /// </summary>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static byte[] ObjectToByte(object obj)
        {
            if (obj == null) return new byte[0];

            byte[] bytes;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, obj);
                bytes = memoryStream.GetBuffer();
            }
            return bytes;
        }


    }
}
